﻿#include "uiregister.h"
#include "ui_uiregister.h"

#include <login/cuserinfomgr.h>
#include "../uimain_window.h"
UiRegister::UiRegister(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UiRegister)
{
    ui->setupUi(this);
    init();
}

UiRegister::~UiRegister()
{
    delete ui;
}

void UiRegister::init() {
    this->resize(1024, 600);

    connect(ui->btn_register, &QPushButton::clicked, this, &UiRegister::onRegister);

    connect(ui->btn_login, &QPushButton::clicked, this, &UiRegister::onLogin);

    connect(ui->btn_goRegister, &QPushButton::clicked, this, &UiRegister::onGoRegister);

    connect(ui->btn_goLogin, &QPushButton::clicked, this, &UiRegister::onGoLogin);

    onGoLogin();
}

void UiRegister::onRegister() {
    QString nikeName = ui->let_nikename->text();;
    QString user = ui->let_user->text();
    QString pwd = ui->let_pwd->text();
    QString emailAddress = ui->let_addr->text();
    QString phoneNumber = ui->let_phone->text();

    if(nikeName.isEmpty() || user.isEmpty() || pwd.isEmpty() || emailAddress.isEmpty() || phoneNumber.isEmpty()) {
        QMessageBox::warning(nullptr, "错误", "校验错误，请重新输入后提交！");
        return;
    }

    QJsonObject root;
    root["userid"] = user;
    root["pwd"] = pwd;
    root["nickname"] = nikeName;
    root["utype"] = 1;
    root["admin_usr"] = "admin";
    root["configs"] = QJsonObject();
    root["menu_permission"] = QJsonObject();
    root["property_permission"] = QJsonObject();
    root["groupings"] = "root";
    root["create_time"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    root["update_time"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    root["last_online_time"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    root["last_login_time"] = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    root["email_address"] = emailAddress;
    root["phone_number"] = phoneNumber;

    QByteArray value = QJsonDocument(root).toJson(QJsonDocument::Indented);

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QUrl url(ADDR + "/api/userMgr/userRegister");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QNetworkReply *reply = manager->post(request, value);

    connect(reply, &QNetworkReply::finished, [reply, this]() {
        if (reply->error() != QNetworkReply::NoError) {
            qDebug() << "Error:" << reply->errorString();
            QMessageBox::warning(nullptr, "错误", "校验错误，请重新输入后提交！");
        } else {
            QString responseString = QString::fromUtf8(reply->readAll());
            this->onGoLogin();
        }
        reply->deleteLater(); // 请求完成后，记得删除 reply 对象
    });
}

void UiRegister::onLogin() {
#if TEST
    if(ui->let_login_usr->text().isEmpty() || ui->let_login_pwd->text().isEmpty()) {
        QMessageBox::warning(nullptr, "错误", "账户名和密码不能为空！");
        return;
    }

    QJsonObject root;
    root["userid"] = ui->let_login_usr->text();
    root["pwd"] = ui->let_login_pwd->text();

    QByteArray value = QJsonDocument(root).toJson().data();

    QNetworkAccessManager *manager = new QNetworkAccessManager(this);
    QUrl url(ADDR + "/api/userMgr/userLogin");
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QNetworkReply *reply = manager->post(request, value);

    connect(reply, &QNetworkReply::finished, [reply,this]() {
        if (reply->error() != QNetworkReply::NoError) {
            qDebug() << "Error:" << reply->errorString();
            QMessageBox::warning(nullptr, "错误", "校验错误，请重新输入后提交！");
        } else {
            QByteArray responseData = reply->readAll();
            QJsonDocument jsonResponse = QJsonDocument::fromJson(responseData);
            QJsonObject json = jsonResponse.object();

            CUserInfo info;
            info.fromJson(json);

            CUserInfoMgr& mgr = CUserInfoMgr::ins();
            QString token = json["token"].toString();
            mgr.setInfo(true, info, token);

            UiMainWindow* window = new UiMainWindow;
            window->resize(1920, 1080);
            window->show();
            this->close();
        }
        reply->deleteLater();
    });
#else
    UiMainWindow* window = new UiMainWindow;
    window->resize(1920,1080);
    window->show();
    this->close();
#endif
}

void UiRegister::onGoRegister()
{
    ui->stackedWidget->setCurrentIndex(0);
}

void UiRegister::onGoLogin()
{
    ui->stackedWidget->setCurrentIndex(1);
}
